package com.kingsoft.dc.khaos.extender.meta.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingsoft.dc.khaos.extender.meta.model.TenantInfo;
import com.kingsoft.dc.khaos.extender.meta.utils.HttpUtils;
import com.ksyun.auth.client.AuthenticationHelper;
import com.ksyun.auth.client.Authorize;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import static io.netty.handler.codec.http.HttpHeaders.Values.APPLICATION_JSON;

/**
 * Created by haorenhui on 20/11/04.
 */
public class CmApiUtils {

    private static Logger logger = LoggerFactory.getLogger(CmApiUtils.class);
    final static String AKSK_PATH = "api/aksk";
    final static String PROTOCOL = "http";

    //元数据管理接口-数据热度统计上报-数据状态批量登记
    final static String REPORT_SYNC_PROCESS_DATA = "/api/metrics/di";

    /**
     * @param request
     * @return
     */
    public static TenantInfo getTenantAkSk(CmRequest request) {
        request.setRealUrl(addProtocol(request.getUrl() + "/" + AKSK_PATH + "/" + request.getTenantId()));
        String content = getData(request);
        String result = extractResult(content);
        TenantInfo tenantInfo = JSON.parseObject(result, TenantInfo.class);
        return tenantInfo;
    }

    public static String extractResult(String content) {
        String result = "";
        Map contentMap = JSON.parseObject(content, Map.class);
        if (contentMap.containsKey("status")) {
            int status = Integer.parseInt(contentMap.get("status").toString());
            if (status == 200) {
                result = contentMap.get("result").toString();
            } else {
                logger.warn("the response status not 200,status={}, message={}", contentMap.get("status"), contentMap.get("message"));
            }
        }
        return result;
    }

    public static boolean checkResponseIfSuccess(String content) {
        boolean success = false;
        Map contentMap = JSON.parseObject(content, Map.class);
        if (contentMap.containsKey("status")) {
            int status = Integer.parseInt(contentMap.get("status").toString());
            if (status == 200) {
                success = true;
            } else {
                logger.error("message={}", contentMap.get("message"));
            }
        }
        return success;
    }

    public static String postData(CmRequest request) {
        String content = "";
        if (request.isNeedAuth()) {
            content = HttpUtils.doPost(request.getRealUrl(), getAuthHeader(request.getAuthRequest()), request.getParams());
        } else {
            content = HttpUtils.doPost(request.getRealUrl(), null, request.getParams());
        }
        logger.info("post response content:==>{}" , content);
        return content;

    }


    public static String getData(CmRequest request) {
        String content = "";
        if (request.isNeedAuth()) {
            content = HttpUtils.doGet(request.getRealUrl(), getAuthHeader(request.getAuthRequest()));
        } else {
            content = HttpUtils.doGet(request.getRealUrl(), null);
        }
//        logger.info("get response content:==>{}" , content);
        return content;

    }

    public static String addTenantId(String url) {
        if (!url.startsWith(PROTOCOL)) {
            url = PROTOCOL + "://" + url;
        }
        return url;
    }

    public static String addProtocol(String url) {
        if (!url.startsWith(PROTOCOL)) {
            url = PROTOCOL + "://" + url;
        }
        return url;
    }

    @Authorize(Authorize.Type.PROJECT)
    public static Map getAuthHeader(AuthRequest authRequest) {
        String ak = authRequest.getAk();
        String sk = authRequest.getSk();
        String authServerUrl = authRequest.getAuthUrl();
//        AuthenticationHelper.setDefaultAuthorizeMethod(Authorize.Type.PROJECT);
        AuthenticationHelper.getHeaderInterceptor(ak, sk, authServerUrl);
        String token = AuthenticationHelper.getToken();
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", APPLICATION_JSON);
        headerMap.put("X-AUTH-APP", ak);
        headerMap.put("X-AUTH-TOKEN", token);
        headerMap.put("SOURCE-AK", ak);
        headerMap.put("AUTH-PROJECT-ID", String.valueOf(authRequest.getAuthProjectId()));

        return headerMap;
    }

    /**
     * 上报运维中心指标
     *
     * @param request
     * @return
     */
    public static CmReportResult reportSyncProcessData(CmRequest request) {
        request.setRealUrl(addProtocol(request.getUrl().concat(REPORT_SYNC_PROCESS_DATA)));
        String content = postData(request);
        Map contentMap = JSON.parseObject(content, Map.class);
        if (contentMap.containsKey("status")) {
            int status = Integer.parseInt(contentMap.get("status").toString());
            if (status != 200) {
                logger.warn("the response status not 200,status={}, message={},errMessage={}", contentMap.get("status"), contentMap.get("message"), contentMap.get("errMessage"));
            }
        }
        CmReportResult cmReportResult = JSONObject.parseObject(content, CmReportResult.class);
        return cmReportResult;
    }

}
